<script lang="ts" setup name="GoodsImage">
import { computed, PropType, ref } from 'vue';
import { Position, useMouseInElement } from '@vueuse/core'

defineProps({
  images: {
    type: Array as PropType<string[]>,
    default: () => []
  }
})
//  大图默认展示下标
const activeItem = ref(0)

const target = ref(null)
const { elementX, elementY, isOutside } = useMouseInElement(target)

const position = computed(() => {
  let x = elementX.value - 100
  let y = elementY.value - 100
  if (x < 0) x = 0
  if (x > 200) x = 200
  if (y < 0) y = 0
  if (y > 200) y = 200
  return {
    x,
    y,
  }
})
</script>

<template>
  <div class="goods-image">
    <!-- 左边的商品图片 -->
    <!-- 用户hover的区域 -->
    <div ref="target" class="middle">
      <img :src="images[activeItem]" alt="" />
      <!-- 蒙层 -->
      <div v-show="!isOutside" :style="{ top: position.y + 'px', left: position.x + 'px' }" class="layer"></div>
    </div>
    <!-- 右边hover时才会出现的图片 -->
    <div v-show="!isOutside" class="large" :style="[{
      backgroundImage: `url(${images[activeItem]})`,
      backgroundPosition: `${-position.x * 2}px ${-position.y * 2}px`
    }]">
    </div>
    <ul class="small">
      <li v-for="(item, index) in   images" :key="item" :class="{ active: index === activeItem }"
        @mouseenter="activeItem = index">
        <img :src="item" alt="" />
      </li>
    </ul>
  </div>
</template>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  // 给父盒子设置z-index提升整体的层级
  z-index: 500;

  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }

  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    // 遮罩
    position: relative;
    cursor: move;

    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, .2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }

  .small {
    width: 80px;

    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;

      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>